import axios from "axios";
import { getToken, removeToken } from "@/utils";

import router from "@/router";

export const request = axios.create({
  baseURL: "http://geek.itheima.net/v1_0",
  timeout: 10000,
});

request.interceptors.request.use(
  (config) => {
    const data = Object.assign({}, config.headers, {
      Authorization: `Bearer ${getToken("token")}`,
    });
    config.headers = data;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
request.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    console.log(error, "axios");

    if (error.response.status === 401) {
      removeToken();
      router.navigate("/login");
    }
    return Promise.reject(error);
  }
);
